import {
  setRecommenddj,
  setDjinfo,
  setPlayinfo,
  setCanplaylist,
  setPlayprivileges,
  setRecommendlist,
  setRecommendnewsong,
  setRecommend,
  setLikemusiclist,
  setSonginfo
} from './actions'
import {
  getRecomandPark,
  likelist,
  queryDj,
  playDetail,
  getRecommand,
  getDjprogram,
  getNewSong,
  getSongUrl,
  getLyric,
  getSongDetail,
  setlike
} from '../api/base'
import { parse_lrc } from '../utils/index'

export function getrecomandinfo() {
  return async (dispatch) => {
    let { result: play } = await getRecommand()
    let { result: dj } = await getDjprogram()
    let { result: song } = await getNewSong()
    let { result: recommand } = await getRecomandPark()
    dispatch(setRecommenddj(dj))
    dispatch(setRecommendlist(play))
    dispatch(setRecommendnewsong(song))
    dispatch(setRecommend(recommand))
  }
}
export function getSongInfo(id) {
  return async (dispatch) => {
    let { songs } = await getSongDetail({ ids: id })
    let { data } = await getSongUrl({ id })
    let { lrc } = await getLyric({ id })
    let songInfo = songs[0]
    songInfo.url = data[0].url

    let lrcinfo = parse_lrc(lrc && lrc.lyric ? lrc.lyric : '')
    songInfo.lrcInfo = {
      lrc,
      lrclist: lrcinfo.now_lrc,
      scroll: lrcinfo.scroll ? 1 : 0
    }

    dispatch(setSonginfo(songInfo))
  }
}

export function getPlayListDetail(id) {
  return async (dispatch) => {
    let { playlist, privileges } = await playDetail({ id })
    playlist.tracks = DealPlaylist(playlist)
    let canPlayList = playlist.tracks.filter((_, index) => {
      return privileges[index].st !== -200
    })
    dispatch(setPlayinfo(playlist))
    dispatch(setPlayprivileges(privileges))
    dispatch(setCanplaylist(canPlayList))
  }
}
export function getLikeMusicList(uid) {
  return async (dispatch) => {
    let { ids } = await likelist({ uid })
    dispatch(setLikemusiclist(ids))
  }
}
export function likeMusic(like, id) {
  return async (dispatch, getState) => {
    let { likeMusicList } = getState()
    let temp = likeMusicList.slice()
    let i = temp.indexOf(id)
    i > -1 ? temp.splice(i, 1) : temp.push(id)
    await setlike({ like, id })
    dispatch(setLikemusiclist([...likeMusicList, temp]))
  }
}
export function getDjDetail(id) {
  return async (dispatch) => {
    let { program } = await queryDj({ id })
    dispatch(setDjinfo(program))
  }
}
function DealPlaylist(data) {
  return data.tracks.map((e) => {
    let { name, id, ar, al, copyright } = e
    return { name, id, ar, al, copyright }
  })
}
